# -*- coding: utf-8 -*-
import hashlib
import json
import time
import urllib
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.crypt.CryptoHelper import CryptoHelper
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10001365': {  # witch 支付宝3%（10---5000）D0结算
        'API_LABEL': 'e64537b4ae94403c8c06a4a7aae67d98',
        'API_KEY': '12eeb8f3ece24dd8b7eef4f452423cb9',
        'gateway': 'http://gateway.huihuangd.cn/paygateway/kfupay/order/v1?merAccount={}&data={}',
        'query_gateway': 'https://gateway.huihuangd.cn/paygateway/kfupay/order/query/v1_1?merAccount={}&data={}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_api_label(mch_id):
    return APP_CONF[mch_id]['API_LABEL']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.sha1()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            s += str(parameter[k])
    s += key
    _LOGGER.info("kpay sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("kpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 支付方式，
# 银联：UNIONPAY，
# 微信：WEIXIN，
# QQ钱包：QQPAY，
# 支付宝：ALIPAY

# SCANPAY_UNIONPAY	银联扫码
# SCANPAY_WEIXIN	微信扫码支付
# SCANPAY_ALIPAY	支付宝扫码支付
# SCANPAY_QQ	QQ钱包扫码支付
# H5_QQ	QQH5
# ALIPAY_H5	支付宝H5
# H5_WEIXIN	微信H5

def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'WEIXIN', 'H5_WEIXIN'
    elif service == 'alipay':
        payType = 'ALIPAY', 'ALIPAY_H5'
    elif service == 'qq':
        payType = 'QQPAY', 'H5_QQ'
    elif service == 'quick':
        payType = 'UNIONPAY', 'SCANPAY_UNIONPAY'
    else:
        payType = 'UNIONPAY', 'SCANPAY_UNIONPAY'
    return payType


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    payWay, payType = _get_pay_type(service)
    parameter_dict = OrderedDict((
        ('merAccount', _get_api_label(app_id)),
        ('merNo', app_id),
        ('orderId', str(pay.id)),
        ('time', int(time.time())),
        ('amount', str(int(pay_amount * 100))),
        ('productType', '01'),
        ('product', 'charge'),
        ('productDesc', 'charge'),
        ('userType', 0),
        ('payWay', payWay),
        ('payType', payType),
        ('userIp', _get_device_ip(info)),
        ('returnUrl',
         urllib.quote('{}/pay/api/{}/kpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id)))),
        ('notifyUrl',
         urllib.quote('{}/pay/api/{}/kpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id))),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    j = json.dumps(parameter_dict, separators=(',', ':'))
    crypto = CryptoHelper()
    data = crypto.aes_encrypt(j, api_key)
    url = _get_gateway(app_id).format(parameter_dict['merAccount'], data)
    _LOGGER.info("kpay create: %s, %s", url, j)
    response = requests.get(url, timeout=3)
    _LOGGER.info("kpay create rsp: %s", response.text)
    rdata = crypto.aes_decrypt(json.loads(response.text)['data'], api_key)
    _LOGGER.info("kpay create rsp data: %s", rdata)
    order_db.fill_third_id(pay.id, rdata['mbOrderId'])
    return {'charge_info': json.loads(rdata)['payUrl']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("kpay notify body: %s", request.body)
    data = json.loads(request.body)
    crypto = CryptoHelper()
    rdata = crypto.aes_decrypt(data['data'], api_key)
    verify_notify_sign(rdata, api_key)
    pay_id = data['orderId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('kpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['orderStatus'])
    trade_no = data['mbOrderId']
    total_fee = float(data['amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'SUCCESS':
        _LOGGER.info('kpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merAccount', _get_api_label(app_id)),
        ('mbOrderId', str(pay_order.third_id)),
        ('time', int(time.time())),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)

    crypto = CryptoHelper()
    data = crypto.aes_encrypt(json.dumps(parameter_dict, separators=(',', ':')), api_key)
    url = _get_query_gateway(app_id).format(parameter_dict['merAccount'], data)
    _LOGGER.info('kpay query data, %s', url)
    response = requests.get(url, timeout=3)
    _LOGGER.info("kpay query rsp: %s", response.text)
    rdata = crypto.aes_decrypt(json.loads(response.text)['data'], api_key)
    _LOGGER.info("kpay query rsp data: %s", rdata)
    if response.status_code == 200:
        mch_id = pay_order.mch_id
        trade_status = str(rdata['status'])
        total_fee = float(rdata['amount'])
        trade_no = rdata['mbOrderId']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 订单状态，0-未支付 1-支付成功 2-已撤销 3-阻断交易 4-失败 5-处理中
        if trade_status == '1':
            _LOGGER.info('kpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
